package com.chenglu.android.index.selectcity.citypicker;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;


import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.services.core.LatLonPoint;
import com.chenglu.android.R;
import com.chenglu.android.common.base.BaseFullScreenActivity;
import com.chenglu.android.common.net.Constant;
import com.chenglu.android.common.utils.LogUtils;
import com.chenglu.android.common.utils.SPUtils;
import com.chenglu.android.common.utils.StatusBarUtil;
import com.chenglu.android.common.utils.ToastUtils;
import com.chenglu.android.index.selectcity.citypicker.adapter.CityListAdapter;
import com.chenglu.android.index.selectcity.citypicker.adapter.ResultListAdapter;
import com.chenglu.android.index.selectcity.citypicker.db.DBManager;
import com.chenglu.android.index.selectcity.citypicker.model.City;
import com.chenglu.android.index.selectcity.citypicker.model.LocateState;
import com.chenglu.android.index.selectcity.citypicker.model.MyCity;
import com.chenglu.android.index.selectcity.citypicker.utils.StringUtils;
import com.chenglu.android.index.selectcity.citypicker.view.SideLetterBar;
import com.google.gson.Gson;
import com.gyf.immersionbar.ImmersionBar;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;


import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @author: lyj
 * @Created: by Copyright 2023/10/21 Guangzhou Hongma Technology Co., Ltd. All rights reserved.
 * @Description： 城市选择
 */
public class CityPickerActivity extends BaseFullScreenActivity implements View.OnClickListener {
    public static final String KEY_PICKED_CITY = "picked_city";

    private LinearLayout mSearchLayout;
    private LinearLayout mLeftLayout;
    private ListView mListView;
    private ListView mResultListView;
    private SideLetterBar mLetterBar;
    private EditText searchBox;
    private ImageView clearBtn;
    private TextView cancelBtn;
    private ViewGroup emptyView;

    private CityListAdapter mCityAdapter;
    private ResultListAdapter mResultAdapter;
    private List<City> mAllCities;
    private List<City> mResultCities;
    private DBManager dbManager;


    public static final Boolean HIDE_ALL_CITY = false;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.cp_activity_city_list);

//        setStatusBar(this.getResources().getColor(R.color.businesstop));
        initData();
        initView1();

//        initLocation();

        boolean aBoolean = SPUtils.getBoolean(Constant.ISLOCATION, true);

        if (aBoolean == true) {
            requestPermission1();

        } else {
            //通过就给位置权限
            if (XXPermissions.isGranted(mContext, Permission.ACCESS_FINE_LOCATION, Permission.ACCESS_COARSE_LOCATION)) {
                getCurrentLocationLatLng();
            }
        }


        ImmersionBar.with(this)
                .statusBarColor(R.color.transparent)
                .statusBarDarkFont(true)
                .fullScreen(true)
                .init();

        Toolbar toolbar = findViewById(R.id.toolbar);

        StatusBarUtil.immersive(this);
        StatusBarUtil.setPaddingSmart(this, toolbar);

        //请求权限
//        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M){
//            mLocationClient.startLocation();
//        }else {
//            requestPermissions(this, neededPermissions, this);
//        }
        mResultCities = new ArrayList<>();
    }


    private void initData() {

        List<MyCity.Data> studentData = getStudentData(this);

        mAllCities = new ArrayList<>();

        for (int i = 0; i < studentData.size(); i++) {
            City city = new City(studentData.get(i).getName(), studentData.get(i).getPinyin());
            mAllCities.add(city);
        }
//        dbManager = new DBManager(this);
//        dbManager.copyDBFile();
//        mAllCities = dbManager.getAllCities();
//        mAllCities.clear();

        mCityAdapter = new CityListAdapter(this, mAllCities);
        mCityAdapter.setOnCityClickListener(new CityListAdapter.OnCityClickListener() {
            @Override
            public void onCityClick(String name) {
                backWithData(name);
            }

            @Override
            public void onLocateClick() {
                mCityAdapter.updateLocateState(LocateState.LOCATING, null);
                requestPermission1();
//                requestPermissions(CityPickerActivity.this, neededPermissions, CityPickerActivity.this);
            }
        });

        mResultAdapter = new ResultListAdapter(this, null);
    }

    public String loadJSONFromAsset(Context context, String fileName) {
        String json = null;
        try {
            InputStream inputStream = context.getAssets().open(fileName);
            int size = inputStream.available();
            byte[] buffer = new byte[size];
            inputStream.read(buffer);
            inputStream.close();
            json = new String(buffer, "UTF-8");
        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
        return json;
    }

    /**
     * 解析json数据
     *
     * @param context
     * @return
     */
    public List<MyCity.Data> getStudentData(Context context) {

        MyCity myBean = new Gson().fromJson(loadJSONFromAsset(context, "citylist.json"), MyCity.class);
//        Toast.makeText(context, "code:" + myBean.getName()+ "，Message:" + myBean.getMessage(), Toast.LENGTH_LONG).show();

        final List<MyCity.Data> dataBeans = myBean.getData();
        return dataBeans;

    }


    private void initView1() {
        mLeftLayout = (LinearLayout) findViewById(R.id.ll_back);
        mLeftLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mListView = (ListView) findViewById(R.id.listview_all_city);
        mListView.setAdapter(mCityAdapter);
        mSearchLayout = (LinearLayout) findViewById(R.id.search_layout);
        TextView overlay = (TextView) findViewById(R.id.tv_letter_overlay);
        mLetterBar = (SideLetterBar) findViewById(R.id.side_letter_bar);
        mLetterBar.setOverlay(overlay);
        mLetterBar.setOnLetterChangedListener(new SideLetterBar.OnLetterChangedListener() {
            @Override
            public void onLetterChanged(String letter) {
//                ToastUtils.show("dddd=" + letter);
                int position = mCityAdapter.getLetterPosition(letter);
                mListView.setSelection(position);
            }
        });

        searchBox = (EditText) findViewById(R.id.et_search);
        searchBox.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                String keyword = s.toString();
                if (TextUtils.isEmpty(keyword)) {
                    clearBtn.setVisibility(View.GONE);
                    emptyView.setVisibility(View.GONE);
                    mResultListView.setVisibility(View.GONE);
                } else {
                    clearBtn.setVisibility(View.VISIBLE);
                    mResultListView.setVisibility(View.VISIBLE);
                    List<MyCity.Data> studentData = getStudentData(mContext);
                    Pattern pattern = Pattern.compile(keyword, Pattern.CASE_INSENSITIVE);

                    for (int i = 0; i < studentData.size(); i++) {

                        if (pattern.matcher(studentData.get(i).getName()).matches()) {
                            if (!mResultCities.isEmpty()) {
                                mResultCities.clear();
                            }
                            City city = new City(studentData.get(i).getName(), studentData.get(i).getPinyin());
                            mResultCities.add(city);
                        }

                    }
//                    mResultCities = dbManager.searchCity(keyword);
                    if (mResultCities == null || mResultCities.size() == 0) {
                        emptyView.setVisibility(View.VISIBLE);
                    } else {
                        emptyView.setVisibility(View.GONE);
                        mResultAdapter.changeData(mResultCities);
                    }
                }
            }
        });

        emptyView = (ViewGroup) findViewById(R.id.empty_view);
        mResultListView = (ListView) findViewById(R.id.listview_search_result);
        mResultListView.setAdapter(mResultAdapter);
        mResultListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                backWithData(mResultAdapter.getItem(position).getName());
            }
        });

        clearBtn = (ImageView) findViewById(R.id.iv_search_clear);
//        cancelBtn = (TextView) findViewById(R.id.tv_search_cancel);

        clearBtn.setOnClickListener(this);
//        cancelBtn.setOnClickListener(this);

        if (HIDE_ALL_CITY) {
            mSearchLayout.setVisibility(View.GONE);
            mLetterBar.setVisibility(View.GONE);
        }
    }

    private void backWithData(String city) {
        Intent data = new Intent();
        data.putExtra(KEY_PICKED_CITY, city);
        setResult(RESULT_OK, data);
        finish();
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.iv_search_clear) {
            searchBox.setText("");
            clearBtn.setVisibility(View.GONE);
            emptyView.setVisibility(View.GONE);
//            mResultListView.setVisibility(View.GONE);
            mResultCities = null;
        }
    }


    //********************         start                ******************//

//    private void initLocation() {
//        try {
//            mLocationClient = new AMapLocationClient(this);
//
//            AMapLocationClientOption option = new AMapLocationClientOption();
//            option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
//            option.setOnceLocation(true);
//            mLocationClient.setLocationOption(option);
//            mLocationClient.setLocationListener(new AMapLocationListener() {
//                @Override
//                public void onLocationChanged(AMapLocation aMapLocation) {
//                    if (aMapLocation != null) {
//                        if (aMapLocation.getErrorCode() == 0) {
//                            String province = aMapLocation.getProvince();
//                            String city = aMapLocation.getCity();
//                            String district = aMapLocation.getDistrict();
//                            String location = StringUtils.extractLocation(city, district);
//
//                            LogUtils.e("citt="+ city + district +location );
//                            mCityAdapter.updateLocateState(LocateState.SUCCESS, location);
//                        } else {
//                            //定位失败
//                            mCityAdapter.updateLocateState(LocateState.FAILED, null);
//                        }
//                    }
//                }
//            });
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//    }
    //********************         end                ******************//

    private void requestPermission1() {
        XXPermissions.with(this)
                // 申请单个权限
                .permission(Permission.ACCESS_FINE_LOCATION)
                .permission(Permission.ACCESS_COARSE_LOCATION)
                // 申请多个权限
//                .permission(Permission.WRITE_EXTERNAL_STORAGE)
                // 设置权限请求拦截器（局部设置）
                //.interceptor(new PermissionInterceptor())
                // 设置不触发错误检测机制（局部设置）
//                .unchecked()
                .request(new OnPermissionCallback() {

                    @Override
                    public void onGranted(@NonNull List<String> permissions, boolean allGranted) {
                        SPUtils.setBoolean(Constant.ISLOCATION, false);
                        getCurrentLocationLatLng();

                    }

                    @Override
                    public void onDenied(@NonNull List<String> permissions, boolean doNotAskAgain) {
                        SPUtils.setBoolean(Constant.ISLOCATION, false);
                        Toast.makeText(mContext, "权限被禁用，请到设置里打开", Toast.LENGTH_SHORT).show();
                        mCityAdapter.updateLocateState(LocateState.FAILED, null);
                    }
                });


    }

    //声明AMapLocationClient类对象
    AMapLocationClient mLocationClient = null;
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;

    /**
     * 初始化定位并设置定位回调监听
     */
    private void getCurrentLocationLatLng() {
        //初始化定位
        try {
            mLocationClient = new AMapLocationClient(getApplicationContext());
        } catch (Exception e) {
            e.printStackTrace();
        }
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();

 /* //设置定位场景，目前支持三种场景（签到、出行、运动，默认无场景） 设置了场景就不用配置定位模式等
    option.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.SignIn);
    if(null != locationClient){
        locationClient.setLocationOption(option);
        //设置场景模式后最好调用一次stop，再调用start以保证场景模式生效
        locationClient.stopLocation();
        locationClient.startLocation();
    }*/
        // 同时使用网络定位和GPS定位,优先返回最高精度的定位结果,以及对应的地址描述信息
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //只会使用网络定位
        /* mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);*/
        //只使用GPS进行定位
        /*mLocationOption.setLocationMode(AMapLocationMode.Device_Sensors);*/
        // 设置为单次定位 默认为false
        mLocationOption.setOnceLocation(true);
        //设置定位间隔,单位毫秒,默认为2000ms，最低1000ms。默认连续定位 切最低时间间隔为1000ms
        mLocationOption.setInterval(3500);
        //设置是否返回地址信息（默认返回地址信息）
        /*mLocationOption.setNeedAddress(true);*/
        //关闭缓存机制 默认开启 ，在高精度模式和低功耗模式下进行的网络定位结果均会生成本地缓存,不区分单次定位还是连续定位。GPS定位结果不会被缓存。
        /*mLocationOption.setLocationCacheEnable(false);*/
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }

    /**
     * 定位回调监听器
     */

    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            //检查位置权限
//            if (!IsGpsWork.isGpsEnabled(getApplicationContext())) {
//
//                ToastUtils.show("请打开GPS");
//            } else {
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    //定位成功回调信息，设置相关消息
                    amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                    double currentLat = amapLocation.getLatitude();//获取纬度
                    double currentLon = amapLocation.getLongitude();//获取经度


                    String province = amapLocation.getProvince();
                    String city = amapLocation.getCity();
                    String district = amapLocation.getDistrict();
                    String location = StringUtils.extractLocation(city, district);

                    LogUtils.e("citt=" + city + district + location);
                    mCityAdapter.updateLocateState(LocateState.SUCCESS, location);

                    //存取当前经纬度
                    SPUtils.setString(Constant.CURRENTLAT, Double.toString(currentLat));
                    SPUtils.setString(Constant.CURRENTLON, Double.toString(currentLon));

                    LogUtils.i("currentLat : " + currentLat + " currentLon : " + currentLon + "gaode:" + city);
                    amapLocation.getAccuracy();//获取精度信息
                } else {
                    //                            //定位失败
                    mCityAdapter.updateLocateState(LocateState.FAILED, null);
                    //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                    LogUtils.e("location Error, ErrCode:" + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo());
                }
            }
        }
//        }
    };


}
